package com.jl.jlapp.mvp.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog.Builder;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jl.jlapp.R;
import com.jl.jlapp.db.DatabaseHelper;
import com.jl.jlapp.eneity.VersionMessageModel;
import com.jl.jlapp.mvp.base.MyApplication;
import com.jl.jlapp.nets.CommonObserver;
import com.jl.jlapp.nets.Net;
import com.jl.jlapp.popu.ClearHistorySearhPopu;
import com.jl.jlapp.service.DownloadService;
import com.jl.jlapp.utils.DataCleanManager;
import com.jl.jlapp.utils.Tools;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class SettingsActivity extends Activity {
    private static final int DOWN_ERROR = 2;
    private static final int GET_UNDATAINFO_ERROR = 1;
    private static String[] PERMISSIONS_STORAGE = {"android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE"};
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static final int UPDATA_CLIENT = 0;
    String cache = "";
    @BindView(R.id.clear_cache_rela)
    RelativeLayout clearCacheRela;
    ClearHistorySearhPopu clearHistorySearhPopu;
    @BindView(R.id.clear_localhost_cashe_num)
    TextView clearLocalhostCasheNum;
    DatabaseHelper dbHelper;
    Editor editor;
    @BindView(R.id.icon_return)
    ImageView iconReturn;
    public View.OnClickListener itemclick = new View.OnClickListener() {
        public void onClick(View paramAnonymousView) {
            SettingsActivity.this.clearHistorySearhPopu.dismiss();
            DataCleanManager.clearAllCache(SettingsActivity.this);
            Toast.makeText(SettingsActivity.this, "清除成功", Toast.LENGTH_SHORT).show();
            try {
                SettingsActivity.this.cache = DataCleanManager.getTotalCacheSize(SettingsActivity.this);
                SettingsActivity.this.clearLocalhostCasheNum.setText(SettingsActivity.this.cache);
                SettingsActivity.this.dbHelper.delete(SettingsActivity.this.sqliteDatabase);
            } catch (Exception e) {

            }
        }
    };
    public View.OnClickListener itemclick2 = new View.OnClickListener() {
        public void onClick(View paramAnonymousView) {
            SettingsActivity.this.clearHistorySearhPopu.dismiss();
            if (SettingsActivity.this.sharedPreferences == null) {
                SettingsActivity.this.sharedPreferences = SettingsActivity.this.getSharedPreferences("JLAppData", 0);
            }
            SettingsActivity.this.editor = SettingsActivity.this.sharedPreferences.edit();
            SettingsActivity.this.editor.clear();
            SettingsActivity.this.editor.commit();
            Tools.finishAll();
            Intent intent = new Intent(SettingsActivity.this, BaseActivity.class);
            intent.putExtra("shouldReplaceFragment", 3);
            SettingsActivity.this.startActivity(intent);
        }
    };
    String picUrl = "";
    SharedPreferences sharedPreferences;
    SQLiteDatabase sqliteDatabase;
    @BindView(R.id.user_message_setting_rela)
    RelativeLayout userMessageSetting;
    String userName = "";
    @BindView(R.id.user_name)
    TextView userNameTv;
    @BindView(R.id.user_pic)
    ImageView userPic;
    @BindView(R.id.version_check)
    RelativeLayout versionCheck;
    @BindView(R.id.version_checking_unit)
    TextView versionCheckingUnit;
    VersionMessageModel.ResultDataBean versionMessageBean = null;
    String versionName = "0";

    public static File getFileFromServer(String paramString, ProgressDialog paramProgressDialog)
            throws Exception {
        if (Environment.getExternalStorageState().equals("mounted")) {
            HttpURLConnection connection = (HttpURLConnection) new URL(paramString).openConnection();
            connection.setConnectTimeout(5000);
            paramProgressDialog.setMax(connection.getContentLength());
            InputStream inputStream = connection.getInputStream();
            File localFile = new File(Environment.getExternalStorageDirectory(), "jlfood.apk");
            FileOutputStream localFileOutputStream = new FileOutputStream(localFile);
            BufferedInputStream localBufferedInputStream = new BufferedInputStream(inputStream);
            byte[] arrayOfByte = new byte[1024];
            int i = 0;
            for (; ; ) {
                int j = localBufferedInputStream.read(arrayOfByte);
                if (j == -1) {
                    break;
                }
                localFileOutputStream.write(arrayOfByte, 0, j);
                i += j;
                paramProgressDialog.setProgress(i);
            }
            localFileOutputStream.close();
            localBufferedInputStream.close();
            inputStream.close();
            return localFile;
        }
        return null;
    }

    private void getNewVersionMessage() {
        Net.get().getNewVersionMessage(0).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CommonObserver<VersionMessageModel>() {
                    @Override
                    protected void onError(String errorMsg) {

                    }

                    @Override
                    protected void onSuccess(VersionMessageModel versionMessageModel) {
                        if (versionMessageModel.getCode() == 200) {
                            versionMessageBean = versionMessageModel.getResultData();
                        }
                    }
                });
    }

    private String getVersionName()
            throws Exception {
        PackageInfo localPackageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
        Log.d("TAG", "版本号" + localPackageInfo.versionCode);
        Log.d("TAG", "版本名" + localPackageInfo.versionName);
        Editor localEditor = getSharedPreferences("JLAppData", 0).edit();
        localEditor.putInt("versionCode", localPackageInfo.versionCode);
        localEditor.putString("versionName", localPackageInfo.versionName);
        localEditor.commit();
        return localPackageInfo.versionName;
    }

    private void noMustChange() {
        Builder localBuilder = new Builder(this);
        localBuilder.setTitle("版本升级");
        localBuilder.setMessage("检测到最新版本，请及时更新！");
        localBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt) {
                BaseActivity.IS_CHECK_NO_CHANGE = false;
                paramAnonymousDialogInterface.dismiss();
                DownloadService.startService(MyApplication.getInstance().getApplicationContext(), "http://117.158.178.202:8001/jlapk/jlfood.apk");
                Toast.makeText(SettingsActivity.this, "已在后台下载更新", Toast.LENGTH_SHORT).show();
            }
        });
        localBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt) {
                BaseActivity.IS_CHECK_NO_CHANGE = true;
                paramAnonymousDialogInterface.dismiss();
            }
        });
        localBuilder.create().show();
    }

    public static void verifyStoragePermissions(Activity paramActivity) {
        try {
            if (ActivityCompat.checkSelfPermission(paramActivity, "android.permission.WRITE_EXTERNAL_STORAGE") != 0) {
                ActivityCompat.requestPermissions(paramActivity, PERMISSIONS_STORAGE, 1);
            }
        } catch (Exception e) {
        }
    }

    @OnClick({R.id.user_message_setting_rela, R.id.icon_return, R.id.clear_cache_rela, R.id.logout, R.id.message_setting_rela, R.id.version_check})
    public void onClick(View paramView) {
        switch (paramView.getId()) {
            case R.id.user_message_setting_rela:
                startActivity(new Intent(this, UserMessageSettingsActivity.class));
                break;
            case R.id.icon_return:
                finish();
                break;
            case R.id.clear_cache_rela:
                this.clearHistorySearhPopu = new ClearHistorySearhPopu(this, this.itemclick, Integer.valueOf(6));
                this.clearHistorySearhPopu.showAtLocation(findViewById(R.id.setting), 17, 0, 0);
                break;
            case R.id.version_check:
                if (this.versionMessageBean != null) {
                    try {
                        if (this.versionMessageBean.getVersionName().equals(this.versionName)) {
                            Toast.makeText(this, "已是最新版本", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    } catch (Exception e) {
                        Toast.makeText(this, "下载失败", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    verifyStoragePermissions(this);
                    if (this.versionMessageBean.getIsMustUpdate() == 0) {
                        noMustChange();
                        return;
                    }
                    new CheckVersionTask().run();
                } else {
                    Toast.makeText(this, "版本检测失败", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.logout:
                this.clearHistorySearhPopu = new ClearHistorySearhPopu(this, this.itemclick2, Integer.valueOf(7));
                this.clearHistorySearhPopu.showAtLocation(findViewById(R.id.setting), 17, 0, 0);
                break;
        }
    }

    protected void onCreate(Bundle paramBundle) {
        super.onCreate(paramBundle);
        setContentView(R.layout.activity_settings);
        ButterKnife.bind(this);
        Tools.addActivity(this);
        getNewVersionMessage();
        try {
            getVersionName();
            if (this.dbHelper == null) {
                this.dbHelper = new DatabaseHelper(this);
                this.sqliteDatabase = this.dbHelper.getWritableDatabase();
            }
        } catch (Exception e) {
        }
    }

    protected void onResume() {
        super.onResume();
        this.sharedPreferences = getSharedPreferences("JLAppData", 0);
        this.picUrl = this.sharedPreferences.getString("userPicUrl", "userPicUrl");
        this.userName = this.sharedPreferences.getString("userName", "");
        this.userNameTv.setText(this.userName);
        Tools.setCircleIcon("http://117.158.178.202:8001/JLMIS/" + this.picUrl, this.userPic);
        try {
            this.cache = DataCleanManager.getTotalCacheSize(this);
            this.versionName = this.sharedPreferences.getString("versionName", "");
            this.clearLocalhostCasheNum.setText(this.cache);
            this.versionCheckingUnit.setText(this.versionName);
            return;
        } catch (Exception localException) {
        }
    }

    public class CheckVersionTask implements Runnable {
        Handler handler = new Handler() {
            public void handleMessage(Message paramAnonymousMessage) {
                super.handleMessage(paramAnonymousMessage);
                switch (paramAnonymousMessage.what) {
                    case 0:
                        CheckVersionTask.this.showUpdataDialog();
                        break;
                    case 1:
                        Toast.makeText(SettingsActivity.this, "获取服务器更新信息失败", Toast.LENGTH_LONG).show();
                        CheckVersionTask.this.LoginMain();
                        break;
                    default:
                        Toast.makeText(SettingsActivity.this, "下载新版本失败", Toast.LENGTH_LONG).show();
                        CheckVersionTask.this.LoginMain();
                        break;
                }

            }
        };

        public CheckVersionTask() {
        }

        private void LoginMain() {
            Intent localIntent = new Intent(SettingsActivity.this, BaseActivity.class);
            SettingsActivity.this.startActivity(localIntent);
            Tools.finishAll();
        }

        protected void downLoadApk() {
            final ProgressDialog localProgressDialog = new ProgressDialog(SettingsActivity.this);
            localProgressDialog.setProgressStyle(1);
            localProgressDialog.setMessage("正在下载更新");
            localProgressDialog.setCancelable(false);
            localProgressDialog.show();
            new Thread() {
                public void run() {
                    try {
                        File localFile = SettingsActivity.getFileFromServer("http://117.158.178.202:8001/jlapk/jlfood.apk", localProgressDialog);
                        CheckVersionTask.this.installApk(localFile);
                        localProgressDialog.dismiss();
                    } catch (Exception localException) {
                        Message localMessage = new Message();
                        localMessage.what = 2;
                        CheckVersionTask.this.handler.sendMessage(localMessage);
                    }
                }
            }.start();
        }

        protected void installApk(File paramFile) {
            Intent localIntent = new Intent("android.intent.action.VIEW");
            if (Build.VERSION.SDK_INT >= 24) {
                Uri uri = FileProvider.getUriForFile(MyApplication.getInstance().getApplicationContext(), "com.jl.jlapp.fileprovider", paramFile);
                localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                localIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                localIntent.setDataAndType(uri, "application/vnd.android.package-archive");
            } else {
                SettingsActivity.this.startActivity(localIntent);
                localIntent.setDataAndType(Uri.fromFile(paramFile), "application/vnd.android.package-archive");
                localIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }
        }

        public void run() {
            try {
                if (SettingsActivity.this.versionMessageBean.getVersionName().equals(SettingsActivity.this.versionName)) {
                    Toast.makeText(SettingsActivity.this, "已是最新版本", Toast.LENGTH_SHORT).show();
                    return;
                }
                Message localMessage1 = new Message();
                localMessage1.what = 0;
                this.handler.sendMessage(localMessage1);
                return;
            } catch (Exception localException) {
                Message localMessage2 = new Message();
                localMessage2.what = 1;
                this.handler.sendMessage(localMessage2);
            }
        }

        protected void showUpdataDialog() {
            Builder localBuilder = new Builder(SettingsActivity.this);
            localBuilder.setTitle("版本升级");
            localBuilder.setMessage("检测到新版本，部分功能需升级后才可使用，请先升级！");
            localBuilder.setCancelable(false);
            localBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt) {
                    paramAnonymousDialogInterface.dismiss();
                    CheckVersionTask.this.downLoadApk();
                }
            });
            localBuilder.create().show();
        }
    }
}


/* Location:              /Users/davidzhang/Documents/decompileApk/jlfood-dex2jar.jar!/com/jl/jlapp/mvp/activity/SettingsActivity.class
 * Java compiler version: 6 (50.0)
 * JD-Core Version:       0.7.1
 */